#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>

int main()
{
  pid_t id = fork();
  if(id == 0)
  {
    //child
    int cnt  = 10;
    while(cnt)
    {
      printf("child[%d] is running...left %d seconds\n",getpid(),cnt);
      sleep(1);
      cnt--;
    }
    exit(10);
  }
  //基于轮巡检测的非阻塞等待
  while(1)
  {
    int status = 0;
    pid_t ret = waitpid(id, &status, WNOHANG);
    if(ret == 0)
    {
      //waitpid等待成功，但子进程没有退出，需要父进程重复进行等待
      printf("still codeing...do father's things\n"); 
    }
    else if(ret > 0)
    {
      //waitpid等待成功，子进程也退出了，获取到了要的对应结果
      printf("father wait for %d success! status: %d,status exit code: %d,status exit signal:%d\n", ret, status,(status>>8)&0xFF,status&0x7F);
      break;
    }
    else 
    { //ret<0
      //waitpid等待失败(您拨打的电话已关机)
      perror("waitpid");
      break;
    }
    sleep(1);
  }
  ////parent
  //int status = 0;
  //pid_t ret = waitpid(-1,&status,0);  //等待任意一个进程
  //if(ret>0)
  //{
  //  if(WIFEXITED(status))
  //  {
  //    //没有收到任何退出信号
  //    //正常结束，获取对应的退出码
  //    printf("exit code: %d\n", WEXITSTATUS(status));
  //  }
  //  else 
  //  {
  //    printf("error, get a signal\n");
  //  }
  //}
  //sleep(5);
  return 0;
}

    //int a = 10;
    //a /= 0;
  //if(ret>0)
  //  printf("father wait for %d success! status: %d,status exit code: %d,status exit signal:%d\n", ret, status,(status>>8)&0xFF,status&0x7F);
  //else 
  //  printf("father wait failed!\n");

  //sleep(6);//父进程sleep 6s
  
  //printf("father begin to wait!\n");
  //pid_t ret = wait(NULL);
  //pid_t ret = waitpid(id,NULL,0);//等待指定一个进程
  
  //printf("father begin to wait!\n");
  //pid_t ret = wait(NULL);
  //pid_t ret = waitpid(id,NULL,0);//等待指定一个进程
//#include<unistd.h>
//#include<stdlib.h>
//
//int main()
//{
//  printf("have a nice day!");
//  sleep(5);
//  _exit(19);
//  //return 0;
//}
//#include<string.h>
//#include<stdlib.h>
//
//int func()
//{
//  printf("have a nice day!\n");
//  return 1;
//}
//
//int main()
//{
//  func();
//  exit(19);
//  for(int i = 0;i < 140;i++)
//  {
//    printf("%d:%s\n",i,strerror(i));
//  }
//  return 0;
//}
